<template>
    <div class="content" v-loading="loading">
        <!--头部-->
        <div class="header-setting" :style="expendStyle">
            <a-breadcrumb class="breadcrumb">
                <a-breadcrumb-item>
                    <a href="/main">首页</a>
                </a-breadcrumb-item>
                <a-breadcrumb-item>收费管理</a-breadcrumb-item>
                <a-breadcrumb-item>实收明细-{{byType ==='endTime' ? '按离场时间':'按缴费时间'}}</a-breadcrumb-item>
            </a-breadcrumb>
            <!--查询条件-->
            <div class="box-condition-body">
                <div class="box-condition-item">
                    <div style="margin: 0 50px">{{byType ==='endTime' ? '离场时间':'缴费时间'}}</div>
                    <template>
                        <div class="button_time">
                            <a-button @click="button_time(0)" :style="computedStyle(0)">今天</a-button>
                            <a-button @click="button_time(1)" :style="computedStyle(1)">昨天</a-button>
                            <a-button @click="button_time(2)" :style="computedStyle(2)">本周</a-button>
                            <a-button @click="button_time(3)" :style="computedStyle(3)">上周</a-button>
                            <a-button @click="button_time(4)" :style="computedStyle(4)">本月</a-button>
                        </div>
                    </template>
                    <template>
                        <div style="margin: auto 50px">
                            <a-range-picker
                                :showTime="{ format: 'HH:mm:ss' }"
                                format="YYYY-MM-DD HH:mm:ss"
                                :placeholder="['开始时间', '结束时间']"
                                @ok="onOk"
                                @change="onChange"
                                :value="rangePicker()"
                            />
                        </div>
                    </template>
                </div>
               <div class="box-condition-item">
                 <!-- 清除 -->
                    <div style="margin: 0 50px">
                        <a-button style="margin: 0 0 0 20px" @click="reset">重置</a-button>
                    </div>
                </div>
                <div class="box-expand" @click="switchExpend">点击{{isExpand ? '收起' : '展开'}}</div>
            </div>
        </div>

        <!-- 表单 -->
        <div class="box-form">
            <!--工具栏-->
            <div class="box-tool">
                <div></div>
                <div style="display: flex">
                      <a-button @click="exportExcel" icon="download">导出记录</a-button>
                </div>
            </div>
            <!--数据表格-->
            <div class="box-table">

                <a-table :columns="columns"
                         rowKey="no"
                         :dataSource="dataSource"
                         :pagination="pagination"
                         @change="tableChange"
                         bordered size="small"
                         :scroll="scroll"
                         :customRow="customRow"
                         :rowClassName="setRowClassName">
                    <template slot="shouldMoneySlot" slot-scope="text">
                      <div>{{text==undefined||text==''?text:text/100}}</div>
                    </template>
                    <template slot="realityMoneySlot" slot-scope="text">
                      <div>{{text==undefined||text==''?0:text/100}}</div>
                    </template>
                    <template slot="favorableAmountSlot" slot-scope="text">
                      <div>{{text==undefined||text==''?0:text/100}}</div>
                    </template>
                    <template slot="unpaidMoneySlot" slot-scope="text">
                      <div>{{text==undefined||text==''?text:text/100}}</div>
                    </template>
                    <template slot="detail"  slot-scope="text, record">
                      <a-button @click="orderDetail(record)">订单详情</a-button>
                    </template>
                    <!-- 脚步 -->
                </a-table>
            </div>
        </div>


    </div>
</template>

<script>
    // import Constant from '../../utils/Constant';
    import moment from 'moment';
    import CommonApi from "../../api/CommonApi";
    import DaysStatementsDetail from '../../api/charge/DaysStatementsDetail'
    const columns = [
        {
            title: "订单编号",
            dataIndex: "localOrderNo",
        },
        {
            title: "缴费时间",
            dataIndex: "orderTime",
        },
        {
            title: "离场时间",
            dataIndex: "endTime",
        },
        {
            title: "停车点",
            dataIndex: "parkName",
        },
        {
            title: "订单金额（元）",
            dataIndex: "shouldMoney",
            scopedSlots: {customRender: 'shouldMoneySlot'},
        },
        {
            title: "已付（元）",
            dataIndex: "realityMoney",
            scopedSlots: {customRender: 'realityMoneySlot'},
        },
        {
            title: "优惠（元）",
            dataIndex: "favorableAmount",
            scopedSlots: {customRender: 'favorableAmountSlot'},
        },
        {
            title: "未付（元）",
            dataIndex: "unpaidMoney",
            scopedSlots: {customRender: 'unpaidMoneySlot'},
        },
        {
            title: "交易单号",
            dataIndex: "unifyOrderNo",
        },
        {
            title: "商户单号",
            dataIndex: "transactionOrderNo",
        },
        {
          title:'订单详情',
          scopedSlots: {customRender: 'detail'},
        }
    ];

    const dataSource = [];

    const queryCondition = {
        startTime: "",
        endTime: "",
        limit: "100",
        curr: "1",
    };

    export default {
        name: "DaysStatements",

        /*数据层*/
        data() {
            return {
                isExpand: true,
                parks: [],
                selectParkId: [],
                selectId: -1,
                momentArr: [],
                columns: columns,

                dataSource: dataSource,
                /*分页插件*/
                pagination: {
                    showTotal: total => `共${total}条`,
                    total: 0,
                    current: 1,
                    defaultCurrent: 1,
                    showQuickJumper: true,
                    defaultPageSize: 100
                },
                /*表格固定头部*/
                scroll: {
                    y: 550,
                },
                tableState: {
                    rowId: -1,
                },
                /*当前选中的行数据*/
                currRowData: "",
                queryCondition,
                payStatus: 0,
                days:'',
                //按缴费时间或离场时间类型
                byType:'',
                /* 修正弹窗 */
                correctPopupData: {
                    visible: false,
                    loading: false,
                    id: "",
                    imageList: [],
                },
                loading: false,
            }
        },

        /*方法层*/
        methods: {
            /**表格**/
            tableChange(page) {
                this.queryCondition.curr = page.current;
                this.queryData();
                this.queryCondition.curr = 0;
            },
            /*时间按钮控制*/
            button_time(e) {
                this.selectId = e;
                let momentStart;
                let momentEnd;
                switch (e) {
                    case 0:
                        momentStart = moment().startOf('day');
                        momentEnd = moment().endOf('day');
                        break;
                    case 1:
                        momentStart = moment().add('day', -1).startOf('day');
                        momentEnd = moment().add('day', -1).endOf('day');
                        break;
                    case 2:
                        momentStart = moment().week(moment().week()).startOf('week');
                        momentEnd = moment().week(moment().week()).endOf('week');
                        break;

                    case 3:
                        momentStart = moment().week(moment().week() - 1).startOf('week');
                        momentEnd = moment().week(moment().week() - 1).endOf('week');
                        break;
                    case 4:
                        momentStart = moment().month(moment().month()).startOf('month');
                        momentEnd = moment().month(moment().month()).endOf('month');
                        break;
                    default :
                        break;
                }
                this.momentArr[0] = momentStart;
                this.momentArr[1] = momentEnd;
                this.queryData();
            },

            rangePicker() {
                return this.momentArr;
            },


            reset() {
                this.queryData();
            },

            getQueryCondition() {
                let condition = this.queryCondition;
                let startTime = "";
                let endTime = "";
                // condition.payStatus=this.payStatus;
                if (this.momentArr != undefined && this.momentArr.length != 0) {
                    startTime = new Date(this.momentArr[0]).getTime()/1000;
                    endTime = new Date(this.momentArr[1]).getTime()/1000;
                }
                condition.startTime = startTime;
                condition.endTime = endTime;
                return condition;
            },

            /* ---------------- 维度变化 -------------- */
            onChange(date) {
                this.selectId = -1;
                this.momentArr = date;
            },

            onOk() {
                this.selectId = -1;
                this.queryData();
            },

            /* ---------------- 查询 ---------------- */
            queryData() {
                this.loading = true;
                let condition = this.getQueryCondition();
                condition.day = null;
                DaysStatementsDetail.daysStatementsDetail(condition).then((data) => {
                    let { list, total, pageNum, pageSize } = data.data;
                    let array = list || [];
                    array = array.map((item, index) => {
                      return {...item, no: total - (pageNum - 1) * pageSize - index};
                    })
                    this.dataSource = array;
                    this.pagination.total = total;
                    console.info("info=",total)
                    this.pagination.current = pageNum;
                    this.loading = false;
                }).catch(error => {
                    console.log("获取实收明细表数据异常！", error);
                     this.loading = false;
                })
            },
            orderDetail(obj){
              let _this = this;
              // _this.$router.push({ path: '/charge/orderDateil', query:{id:obj.id}});
              let routerJump = _this.$router.resolve({ path: '/charge/orderDateil', query:{id:obj.prid}});
              window.open(routerJump.href, '_blank');
              // this.$router.push(`/charge/orderDateil?data=${obj}`);
            },
            nowTime() {
                let yy = new Date().getFullYear();
                var mm =
                    new Date().getMonth() < 10
                    ? "0" + (new Date().getMonth() + 1)
                    : new Date().getMonth() + 1;
                var dd =
                    new Date().getDate() < 10
                    ? "0" + new Date().getDate()
                    : new Date().getDate();
                let hh = new Date().getHours();
                let mf =
                    new Date().getMinutes() < 10
                    ? "0" + new Date().getMinutes()
                    : new Date().getMinutes();
                let ss =
                    new Date().getSeconds() < 10
                    ? "0" + new Date().getSeconds()
                    : new Date().getSeconds();
               return yy + "-" + mm + "-" + dd + " " + hh + ":" + mf + ":" + ss;
            },
            getTimeDifference( startTime, endTime){
              // let timeData={}
              var timeStr="";
              if(startTime != null  ){
                let sd = startTime.substring(0, 19).replace(/-/g, '/')// 将时间字符串截取到秒，并将其中的-换成/
                let se = '' // 这是定义结束时间，如果为空，就获取当前时间
                let cdate = new Date()
                if( endTime != null  || endTime != ''){
                  se = endTime.substring(0, 19).replace(/-/g, '/')// 将时间字符串截取到秒，并将其中的-换成/
                }else {
                  se = cdate.getTime()
                }
                let sde = new Date(se).getTime()  - new Date(sd).getTime()  // 将时间字符转成时间戳
                if(sde > 1){  // 当有差值时，就计算
                  // let a = (sde/1000 + '').split('.') // 这是获取ms
                  // if(a.length>1){
                  //     // timeData['ms'] = Math.floor(Number('0.'+a[1]*1000))
                  //     if(Math.floor(Number('0.'+a[1]*1000)) >0){
                  //         timeStr=timeStr+Math.floor(Number('0.'+a[1]*1000))+"秒"
                  //     }
                  // }
                  // debugger
                  let d =(sde/1000/60/60/24 +'').split('.') // 这是获取h d
                  if( Number(d[0])!= null &&  Number(d[0])!= ''){
                    timeStr=timeStr+Number(d[0])+"天"
                  }
                  // timeData['d'] = Number(d[0])  // 这是获取d
                  if(d.length>1){
                    // timeData['h'] = Math.floor(Number('0.'+d[1])*24)
                    if( Math.floor(Number('0.'+d[1])*24) >0){
                      timeStr=timeStr+Math.floor(Number('0.'+d[1])*23)+"小时"
                    }
                  }
                  let c = (sde/1000/60/60 +'').split('.')   // 这是获取min
                  if(c.length>1){
                    // timeData['min'] = Math.floor(Number('0.'+c[1])*60)
                    if( Math.floor(Number('0.'+c[1])*60) >0){
                      timeStr=timeStr+ Math.floor(Number('0.'+c[1])*59)+"分"
                    }
                  }
                  let b = (sde/1000/60 +'').split('.')  // 这是获取s
                  if(b.length>1){
                    // timeData['s'] = Math.floor(Number('0.'+b[1])*60)
                    if( Math.floor(Number('0.'+b[1])*60) >0){
                      timeStr=timeStr+ Math.floor(Number('0.'+b[1])*59)+"秒"
                    }
                  }
                }
              }
              return timeStr;
            },

            /* ---------------- 表格 ---------------- */
            customRow(record) {
                return {
                    on: { // 事件
                        click: () => {
                            this.currRowData = record;
                            this.tableState.rowId = record.id;
                        },       // 点击行
                        dblclick: () => {
                            this.showCorrectionPopup(record);
                        }
                    },

                }
            },

            setRowClassName(record) {
                return record.id === this.tableState.rowId ? 'clickRowStyl' : '';
            },

            /* ---------------- 表单功能 ---------------- */
            exportExcel() {
                let condition = this.getQueryCondition();
                DaysStatementsDetail.exportExcel(condition).then((res) => {
                    const link = document.createElement('a');
                    const blob = new Blob([res.data], {type: 'application/vnd.ms-excel'});
                    link.href = URL.createObjectURL(blob);
                    var fileName = decodeURIComponent(res.headers.filename);
                    if(fileName == null || fileName == 'undefined'){
                      fileName = "实收明细表-"+(this.byType ==='endTime' ? '按离场时间':'按缴费时间')+".xlsx";
                    }
                    link.style.display = 'none';

                    link.setAttribute('download', `${fileName}`);
                    link.click();
                    // document.body.removeChild(link) // 下载完成移除元素
                    // window.URL.revokeObjectURL(link.href)
                }).catch(err => {
                    console.log("error")
                    console.log(err)
                    let data = err.data;
                    if (data) {
                        return this.$message.warn(data);
                    }
                });
            },

            /* ---------------- 标题展开 ---------------- */
            switchExpend() {
                this.isExpand = !this.isExpand;
            },

            /* ---------------- 车牌纠正弹窗 ---------------- */
            showCorrectionPopup(item) {
                let {comeInUrl, getOutUrl, id} = item;
                this.correctPopupData.visible = true;
                let imageList = [];
                if (comeInUrl) {
                    let array = comeInUrl.split(',').map(item => {
                        if(item != 'none'){
                            return item;
                        }
                    })
                    imageList.push(...array);
                }
                if (getOutUrl) {
                    let array = getOutUrl.split(',').map(item => {
                          if(item != 'none'){
                            return item;
                        }
                    })
                    imageList.push(...array);
                }
                this.correctPopupData.imageList = imageList;
                this.correctPopupData.loading = false;
                this.correctPopupData.id = id;
            },

            hideCorrectionPopup() {
                this.correctPopupData.visible = false;
            },

            commitCorrect() {
                this.hideCorrectionPopup();
            },

            cancelCorrect() {
                this.hideCorrectionPopup();
            },

        },

        /*计算层*/
        computed: {
            computedStyle() {
                return function (selectId) {
                    return this.selectId == selectId ? "" : "";
                }
            },

            expendStyle() {
                return this.isExpand ? "" : 'height: 150px; overflow: hidden;';
            },
            computedDue() {
                let dataSource = this.dataSource || [];
                let result = 0;
                dataSource.forEach(item => {
                    result += isNaN(parseInt(item.shouldMoney)) ? 0 : parseInt(item.shouldMoney);
                })
                return result / 100;
            },
             computedDueR() {
                let dataSource = this.dataSource || [];
                let result = 0;
                dataSource.forEach(item => {
                    result += isNaN(parseInt(item.realityMoney)) ? 0 : parseInt(item.realityMoney);
                })
                return result / 100;
            },
        },

        /*渲染层*/
        mounted() {
          let obj = this.$route.query.days;
          let byType = this.$route.query.byType;
          this.days = obj;
          this.byType = byType;
          let condition = this.getQueryCondition();
          condition.day = obj;
          condition.byType = byType;
          DaysStatementsDetail.daysStatementsDetail(condition).then((data) => {
            let { list, total, pageNum, pageSize } = data.data;
            let array = list || [];
            array = array.map((item, index) => {
              return {...item, no: total - (pageNum - 1) * pageSize - index};
            })
            this.dataSource = array;
            this.pagination.total = total;
            this.pagination.current = pageNum;
          }).catch(error => {
            console.log("获取实收明细表数据异常！", error);
          })
            // this.button_time(0);
        },
    }
</script>

<style scoped>
    .content {
        width: 100%;
        height: 100%;
    }

    .header-setting {
        position: relative;
        width: 100%;
        height: auto;
        background: #fff;
        padding-bottom: 40px;

    }

    .header-setting .breadcrumb {
        margin-left: 41px;
        padding-top: 15px;
    }

    /* 展开 */
    .box-expand {
        position: absolute;
        bottom: 0;
        left: 0;
        right: 0;
        /* text */
        cursor: pointer;
        line-height: 40px;
        font-size: 15px;
        text-align: center;
        color: #020202;
        background: white;
    }

    /*表格行选中背景颜色*/
    .clickRowStyl {
        background-color: #C1E0FD;
    }

    .box-condition-body {
        padding-top: 15px;
    }

    .box-condition-item {
        display: flex;
        align-items: center;
        min-width: 1500px;
        padding: 10px 0;
    }

    .box-condition-item .box-item {
        display: flex;
        align-items: center;
        justify-content: center;
        margin: 5px 5px 20px 5px;
    }

    .button_time button {
        margin-left: 10px;
    }

    /* 表单 */
    .box-form {
        padding-left: 40px;
        padding-right: 40px;
        min-height: 705px;
        background: #fff;
        margin-top: 8px;
    }

    .box-form .box-tool {
        padding-top: 11px;
        margin: 8px 0;
        width: 100%; /* flex */
        display: flex;
        align-items: center;
        justify-content: space-between;
    }

    /* box-correction-popup */
    .box-correction-popup {
        padding: 20px;
        height: 555px;
        /* flex */
        display: flex;
        align-items: center;
    }

    .box-correction-popup .box-image {
        padding: 0 15px;
        width: 888px;
        height: 500px;
    }

    .box-correction-popup .box-image .icon-image {
        width: 100%;
        height: 100%;
    }

    .box-correction-popup .box-correct {
        margin: 0 15px;
        width: 310px;
        height: 500px;
    }

    .box-correction-popup .box-correct .item-correct {
        margin-top: 20px;
        display: flex;
        align-items: center;
    }

    .box-correction-popup .box-correct .item-correct .text-correct {
        font-weight: 300;
        font-size: 14px;
        width: 100px;
    }

    .box-correction-popup .box-correct .item-correct .text-value {
        font-weight: 300;
        font-size: 14px;
        line-height: 1.428571429;
        color: #020202;
    }
</style>
